<?php

namespace app\admin\controller\coll;

use app\common\model\goods\Goods;
use app\common\controller\Backend;
use app\common\model\purchase\Allot;
use app\common\model\purchase\Diff;
use app\common\model\purchase\Enter;
use app\common\model\purchase\EnterGoods;
use app\common\model\sales\Change;
use app\common\model\sales\Checkout;
use app\common\model\sales\Retreat;
use app\common\model\stock\Loss;
use fast\Tree;
use app\common\model\goods\Cate as CateModel;
use app\common\model\Storehouse;
use app\common\model\goods\GoodsHouseStock;
use app\admin\model\Admin;
use think\Db;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Summary extends Backend
{
    
    /**
     * Anal模型对象
     * @var \app\common\model\coll\Anal
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\coll\Anal;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        return $this->view->fetch();
    }
    public function bakbak(){
        $page = input('page/d',0);
        $pagesize = input('pagesize/d',10);

        $starttime = strtotime(input('starttime'));
        $endtime = strtotime(input('endtime'));
        $pid = input('pid/d',0);
        $storehouse_id = input('storehouse_id/d',0);
        $admin_id = input('admin_id/d',0);
        $goods_id = input('goods_id/d',0);
        $where['eg.createtime'] = array('between time',[$starttime,$endtime]);
        if($pid){
            $where['g.cate_id'] = $pid;
        }
        if($storehouse_id){
            $where['eg.storehouse_id'] = $storehouse_id;
        }
        if($admin_id){
            $where['e.admin_id'] = $admin_id;
        }
        if($goods_id){
            $where['eg.goods_id'] = $goods_id;
        }

        $enters = Db::name('purchase_enter_goods')
            ->field('eg.goods_id')
            ->alias('eg')
            ->join('goods g','eg.goods_id = g.id')
            ->join('purchase_enter e','eg.purchase_enter_id = e.id')
            ->where($where)
            ->select();

        $outgoods = Db::name('sales_checkout_goods')
            ->alias('eg')
            ->field('goods_id')
            ->where($where)
            ->join('goods g','eg.goods_id = g.id')
            ->join('sales_slip e','eg.sales_slip_id = e.id')
            ->select();

//            dump($outgoods);
//            dump($enters);
//            dump($where);
        $ids = [];
        foreach ($outgoods as $v){
            if(!in_array($v['goods_id'],$ids)){
                $ids[] = $v['goods_id'];
            }
        }
        foreach ($enters as $v){
            if(!in_array($v['goods_id'],$ids)){
                $ids[] = $v['goods_id'];
            }
        }
//            dump($ids);
        $datas = [];
        for($i=$page*$pagesize;$i<$pagesize;$i++){
            $row = Db::name('goods')->where(array('id'=>$ids[0]))->find();//商品基础信息
            //入库信息

            //采购
            $list = Db::name('purchase_enter_goods')
                ->field('goods_num,unit_price')
                ->where(array('createtime'=>array('between time',[$starttime,$endtime])))
                ->select();
            $num1=0;
            $price1=0;
            foreach ($list as $v){
                $num1+=$v['goods_num'];
                $price1+=$v['goods_num']*$v['unit_price'];
            }
            //销售退货
            $list2 = Db::name('sales_retreat_goods')
                ->field('goods_num,unit_price')
                ->where(array('createtime'=>array('between time',[$starttime,$endtime])))
                ->select();
            $num2=0;
            $price2=0;
            foreach ($list2 as $v){
                $num2+=$v['goods_num'];
                $price2+=$v['goods_num']*$v['unit_price'];
            }

            //报溢


            //同价调拨


            //销售换货


            //----出库


            exit;

        }



        exit;
    }
    public function results()
    {
        if ($this->request->isAjax()) {
            $page = input('page/d',0);
            $pagesize = input('pagesize/d',10);

            $starttime = strtotime(input('starttime'));
            $endtime = strtotime(input('endtime'));
            $pid = input('pid/d',0);
            $storehouse_id = input('storehouse_id/d',0);
            $admin_id = input('admin_id/d',0);
            $goods_id = input('goods_id/d',0);
            $where['createtime'] = array('between time',[$starttime,$endtime]);

            if($storehouse_id){
                $where['storehouse_id'] = $storehouse_id;
            }
            if($admin_id){
                $where['admin_id'] = $admin_id;
            }

            $gwhere = ['is_del'=>1];
            if($pid){
                $gwhere['cate_id'] = $pid;
            }
            if($goods_id){
                $gwhere['id'] = $goods_id;
            }
            $list = Db::name('goods')
                ->where($gwhere)
                ->limit($page*$pagesize,$pagesize)
                ->select();

            $total = Db::name('goods')->where($gwhere)->count();



            $data = [];
            foreach ($list as $k => $v){
                $where['goods_id'] = $v['id'];
                $logs = Db::name('goods_stock_log')->where($where)->select();
                $end_num = 0;
                $out_num = 0;
                $after_num = 0;

                $swhere = array('goods_id'=>$v['id'],'createtime'=>array('<',$starttime));
                if($storehouse_id >0){
                    $swhere['storehouse_id'] = $storehouse_id;
                }
                $row = Db::name('goods_stock_log')->where($swhere)->order('id','DESC')->find();

                if(empty($row)){//调
                    $lwhere=$where;
                    $lwhere['createtime'] = array('>',$endtime);
                    $logrow = Db::name('goods_stock_log')->where($lwhere)->find();

                    if(!empty($logrow)){
                        $ben_num = $logrow['before_num'];
                        $final_cost = bcdiv($logrow['balance'],$logrow['now_num'],2);
                    }else{
                        $GoodsHouseStock = new GoodsHouseStock;
                        $ben_num = $GoodsHouseStock->getstock($v['id'],$storehouse_id);
                        $gods = new Goods();
                        $final_cost = $gods->getcost($v['id'],$storehouse_id);

                    }
                }else{
                    $ben_num = $row['before_num'];
                }
                dump($v['id']);
                dump($logs);
                if(!empty($logs)){
                    $after_num = $logs[0]['before_num'];
                }else{
                    $lwhere=$where;
                    $lwhere['createtime'] = array('<',$starttime);
                    $logrow = Db::name('goods_stock_log')->where($lwhere)->order('id','DESC')->find();
                    if(!empty($logrow)){
                        $after_num = $logrow['now_num'];
                    }
                }


                foreach ($logs as $val){
                    $end_num += $val['enter_num'];
                    $out_num += $val['out_num'];
                }

                $data[$k] = array(
                    'title'=>$v['title'],
                    'goods_id'=>$v['id'],
                    'number'=>$v['number'],
                    'unit'=>$v['unit'],
                    'specs'=>$v['specs'],
                    'place_origin'=>$v['place_origin'],
                    'enter_num'=>$end_num,
                    'enter_price'=>bcmul($end_num,$final_cost,2),
                    'out_num'=>$out_num,
                    'out_price'=>bcmul($out_num,$final_cost,2),
                    'ben_num'=>$ben_num,
                    'ben_price'=>bcmul($ben_num,$final_cost,2),
                    'after_num'=>$after_num,
                    'after_price'=>bcmul($after_num,$final_cost,2),
                    'final_cost'=>$final_cost,
                );

            }



            return array(
                'data'=>$data,
                'total'=>$total,
            );
            dump($data);
//            dump($list);
            exit;

        }
        $this->assign('list',array(
//            0=>[],
//            1=>[],
//            2=>[],
//            3=>[],
//            4=>[],
        ));
        return $this->view->fetch();
    }
    public function getall(){
        if ($this->request->isAjax()) {
            $page = input('page/d',0);
            $pagesize = input('pagesize/d',10);

            $starttime = strtotime(input('starttime'));
            $endtime = strtotime(input('endtime'));
            $pid = input('pid/d',0);
            $storehouse_id = input('storehouse_id/d',0);
            $admin_id = input('admin_id/d',0);
            $goods_id = input('goods_id/d',0);
            $where['createtime'] = array('between time',[$starttime,$endtime]);

            if($storehouse_id){
                $where['storehouse_id'] = $storehouse_id;
            }
            if($admin_id){
                $where['admin_id'] = $admin_id;
            }

            $gwhere = ['is_del'=>1];
            if($pid){
                $gwhere['cate_id'] = $pid;
            }
            if($goods_id){
                $gwhere['id'] = $goods_id;
            }
            $list = Db::name('goods')
                ->where($gwhere)
                ->limit($page*$pagesize,$pagesize)
                ->select();

            $total = Db::name('goods')->where($gwhere)->count();


            $allprice = 0;
            $data = [];
            foreach ($list as $k => $v){
                $where['goods_id'] = $v['id'];
                $logs = Db::name('goods_stock_log')->where($where)->select();
                $end_num = 0;
                $out_num = 0;
                $after_num = 0;

                $swhere = array('goods_id'=>$v['id'],'createtime'=>array('<',$end_num));
                if($storehouse_id >0){
                    $swhere['storehouse_id'] = $storehouse_id;
                }
                $row = Db::name('goods_stock_log')->where($swhere)->order('id','DESC')->find();
                if(empty($row)){//调
                    $lwhere=$where;
                    $lwhere['createtime'] = array('>',$endtime);
                    $logrow = Db::name('goods_stock_log')->where($lwhere)->find();
                    if(!empty($logrow)){
                        $ben_num = $logrow['before_num'];
                        $final_cost = bcdiv($logrow['balance'],$logrow['now_num'],2);
                    }else{
                        $GoodsHouseStock = new GoodsHouseStock;
                        $ben_num = $GoodsHouseStock->getstock($v['id'],$storehouse_id);
                        $gods = new Goods();
                        $final_cost = $gods->getcost($v['id'],$storehouse_id);
                    }
                }else{
                    $ben_num = $row['before_num'];
                }
                $allprice = bcadd($allprice,bcmul($ben_num,$final_cost,2),2);
            }
            return $allprice;
        }
    }
    public function detaillist(){
        $goods_id = input('goods_id/d', 0);
        $storehouse_id = input('storehouse_id/d', 0);
        $admin_id = input('admin_id/d', 0);
        $starttime = strtotime(input('starttime'));
        $endtime = strtotime(input('endtime'));


        $where = array('goods_id' => $goods_id);
        if ($admin_id) {
            $where['admin'] = $admin_id;
        }
        if ($storehouse_id) {
            $where['storehouse_id'] = $storehouse_id;
        }

        if ($this->request->isAjax()) {
            $where['createtime'] = array('between time', [$starttime, $endtime]);
            $Storehouse = new Storehouse();
            $houses = $Storehouse->select();
            $list = Db::name('goods_stock_log')
                ->where($where)
                ->select();
            $total = Db::name('goods_stock_log')
                ->where($where)
                ->count();
            foreach ($list as $k=>$v){
                foreach ($houses as $val){
                    if($val['id'] == $v['storehouse_id']){
                        $list[$k]['store_name'] = $val['name'];
                    }
                }
                switch ($v['controller']){
                    case 'purchase/enter':
                        $model = new Enter();
                        break;
                    case 'purchase/diff':
                        $model = new Diff();
                        break;
                    case 'purchase/allot':
                        $model = new Allot();
                        break;
                    case 'sales/checkout':
                        $model = new Checkout();
                        break;
                    case 'purchase/retreat':
                        $model = new \app\common\model\purchase\Retreat();
                        break;
                    case 'sales/retreat':
                        $model = new Retreat();
                        break;
                    case 'sales/change':
                        $model = new Change();
                        break;
                    case 'stock/loss':
                        $model = new Loss();
                        break;
                }
                $row = $model->where(array('id'=>$v['type_id']))->find();
                $list[$k]['explain'] = $row['explain'];

//                $list[$k]['price'] = ($v['now_num']+$v['before_num'])*$v['final_cost'];
//                $list[$k]['price'] = $v['now_num']*$v['final_cost'];
                $list[$k]['price'] = $v['balance'];
            }
            return array(
              'rows'=>$list,
              'total'=>$total,
            );

        }
        $grow = Goods::get($goods_id);
        $arow = Admin::get($admin_id);

        $where['createtime'] = array('<', $starttime);
        $list = Db::name('goods_stock_log')
            ->where($where)
            ->find();
        if(empty($list)){
            $num = 0;
            $final_cost = 0;
        }else{
            $num = $list['before_num'];
            $final_cost = $list['final_cost'];
        }
        $hrow = Storehouse::get($storehouse_id);

        $this->assign('gtitle',empty($grow)?'':$grow['title']);
        $this->assign('hname',empty($hrow)?'':$hrow['name']);
        $this->assign('anickname',empty($arow)?'':$arow['nickname']);
        $this->assign('num',$num);
        $this->assign('final_cost',$final_cost);
        return $this->view->fetch();

    }
    public function seach(){
        if ($this->request->isAjax()) {
//              dump(input());
              $data = input();
              $json = json_encode($data);
              $this->success('','',$json);
              exit;

        }
        $tree = Tree::instance();
        $tree->init(collection(CateModel::order('weigh desc,id desc')->select())->toArray(), 'pid');
        $categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');

        $categorydata = [0 => ['type' => 'all', 'name' => __('None')]];
        foreach ($categorylist as $k => $v) {
            $categorydata[$v['id']] = $v;
        }
        $this->view->assign("parentList", $categorydata);

        return $this->view->fetch();
    }
    public function getdetail($ids){
        $row = Db::name('goods_stock_log')
                ->where(array('id'=>$ids))
                ->find();
        return $this->success('','/'.$row['controller'].'/detail?ids='.$row['type_id']);
    }
}
